package com.dragon.logical.service.auth.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.common.util.CovertUtil;
import com.dragon.logical.service.auth.IExamineService;
import com.dragon.logical.service.auth.IModifyLogService;
import com.dragon.logical.service.auth.IToSendService;
import com.dragon.logical.service.auth.PositionService;
import com.dragon.logical.service.avttendance.IAttendanceLeaveService;
import com.dragon.logical.service.contract.ContractService;
import com.dragon.logical.service.contract.DeliverService;
import com.dragon.logical.service.contract.IRefundService;
import com.dragon.logical.service.contract.ProduceService;
import com.dragon.logical.service.customer.CustomerService;
import com.dragon.logical.service.customer.FollowService;
import com.dragon.logical.service.customer.QuotesService;
import com.dragon.logical.service.finance.*;
import com.dragon.logical.service.reminder.IDoReminderService;
import com.dragon.logical.service.supplies.IProcurementService;
import com.dragon.logical.service.supplies.IPurchaseRequisitionService;
import com.dragon.repository.entity.*;
import com.dragon.repository.mapper.*;
import com.google.common.base.Joiner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * <p>
 * 审批操作表 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-07-06
 */
@Service
public class ExamineServiceImpl extends ServiceImpl<ExamineMapper, Examine> implements IExamineService {

    @Autowired
    ExamineMapper mapper;

    @Autowired
    IReimbursementService reimbursementService;

    @Autowired
    ILoanService loanService;

    @Autowired
    ContractService contractService;

    @Autowired
    DeliverService deliverService;

    @Autowired
    CustomerService customerService;

    @Autowired
    QuotesService quotesService;

    @Autowired
    ProduceService produceService;

    @Autowired
    FollowService followService;

    @Autowired
    ICustomerPaymentService customerPaymentService;

    @Autowired
    IPlanCollectService planCollectService;

    @Autowired
    IToSendService toSendService;

    @Autowired
    IDoReminderService reminderService;
    @Autowired
    ToSendMapper toSendMapper;
    @Autowired
    ProduceProductsMapper ppMapper;
    @Autowired
    QuotesProductsMapper qpMapper;
    @Autowired
    PlanCollectMapper planCollectMapper;
    @Autowired
    IPaymentService paymentService;
    @Autowired
    PaymentMapper paymentMapper;
    @Autowired
    ProcurementMapper procurementMapper;
    @Autowired
    PurchaseRequisitionMapper purchaseRequisitionMapper;
    @Autowired
    IPurchaseRequisitionService purchaseRequisitionService;
    @Autowired
    IProcurementService procurementService;
    @Autowired
    IModifyLogService modifyLogService;
    @Autowired
    ProduceMapper produceMapper;
    @Autowired
    RejectedMapper rejectedMapper;
    @Autowired
    IBillService billService;
    @Autowired
    IAttendanceLeaveService attendanceLeaveService;

    @Autowired
    ExamineUserMapper examineUserMapper;

    @Autowired
    ExamineFileMapper examineFileMapper;

    @Autowired
    IRefundService refundService;

    @Autowired
    PositionService positionService;


    @Override
    public Page<Examine> selectApplicantPageList(Integer status, Integer type, Integer applicantId, Integer page, Integer limit) {
        Page<Examine> examinePage = new Page<>(page, limit);
        QueryWrapper<Examine> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(status != null, Examine::getStatus, status)
                .eq(type != null, Examine::getStreamType, type)
                .eq(Examine::getApplicantId, applicantId).orderByDesc(Examine::getCreateTime)
                .groupBy(Examine::getId);
        Page<Examine> examinePage1 = mapper.selectPageList(examinePage, queryWrapper);
        if (examinePage1.getSize() != 0) {
            examinePage1.getRecords().forEach(examine -> {
                Object object = reminderService.selectOperationDetailBy(examine.getStreamType(), examine.getCorrelationId());
                examine.setDetail(object);
            });
        }
        return examinePage1;
    }

    @Override
    public Page<Examine> selectAuditPageList(Integer status, Integer type, Integer auditId, Integer page, Integer limit) {
        Page<Examine> examinePage = new Page<>(page, limit);
        QueryWrapper<Examine> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(status != null, "de.status", status)
                .eq(type != null, "de.stream_type", type)
                .ne("deu.pre_status", 0)
                .eq("deu.audit_user_id", auditId)
                .orderByDesc("de.create_time");
        Page<Examine> examinePage1 = mapper.selectAuditPageList(examinePage, queryWrapper);
        if (examinePage1.getSize() != 0) {
            examinePage1.getRecords().forEach(examine -> {
                Object object = reminderService.selectOperationDetailBy(examine.getStreamType(), examine.getCorrelationId());
                examine.setDetail(object);
            });
        }
        return examinePage1;
    }

    @Override
    public FromDetail selectDetailsById(Integer id, Integer type) {
        // 获取当前一条的基本数据
        FromDetail fromDetail = new FromDetail();
        Examine examine = mapper.selectDetailsById(id, type);
        if (examine == null) {
            examine = new Examine();
            //throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }

        //添加单子的基本信息
        fromDetail.setExamine(examine);
        FromDetail result = assemble(examine, fromDetail, id, type);
        if (result == null) {
            result = new FromDetail();
        }
        return result;
    }

//    @Override
//    public List<Examine> getDetailsList(Integer id, Integer type){
//        QueryWrapper<Examine> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda()
//                .eq(Examine::getStreamType, type)
//                .eq(Examine::getCorrelationId, id)
//                .eq(Examine::getExamineType,0);
//        // 获取流程的基本数据
//        List<Examine> examineList = mapper.selectExamineList(queryWrapper);
//        return examineList;
//    }

    @Override
    public List<Examine> getDetailsList(Integer id, Integer type) {
        // 获取未加签的数据
        QueryWrapper<Examine> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(Examine::getStreamType, type)
                .eq(Examine::getCorrelationId, id)
                .eq(Examine::getExamineType, 0)
                .eq(Examine::getAddSignType, 0);
        // 获取流程的基本数据
        List<Examine> examineList = mapper.selectExamineListByTypeAndMainId(queryWrapper);

        // 获取加签数据
        queryWrapper.clear();
        queryWrapper.lambda()
                .eq(Examine::getStreamType, type)
                .eq(Examine::getCorrelationId, id)
                .eq(Examine::getExamineType, 0)
                .ne(Examine::getAddSignType, 0);
        List<Examine> examineList1 = mapper.selectExamineListByTypeAndMainId(queryWrapper);
        if (examineList1.size() != 0) {
            // 插入到原始数据中去
            for (int i = 0; i < examineList1.size(); i++) {
                Examine examine = examineList1.get(i);

                //获取是加签位置
                Integer index = examineList.stream().filter(ii -> ii.getExamineUserId().equals(examine.getSignUserId())).map(examineList::indexOf).findFirst().get();

                //当前数据是前加签
                if (examine.getAddSignType() == 1) {
                    examineList.add(index, examine);
                }

                //当前数据是后加签
                if (examine.getAddSignType() == 2) {
                    examineList.add(index + i + 1, examine);
                }
            }
        }
        if (examineList.size() != 0) {
            examineList.forEach(examine -> {
                //查询每个审核的附件
                List<ExamineFile> examineFiles = examineFileMapper.selectList(
                        new LambdaQueryWrapper<ExamineFile>().eq(ExamineFile::getExamineUserId, examine.getExamineUserId())
                );
                if (examineFiles.size() != 0) {
                    examine.setExamineFiles(examineFiles);
                }
            });
        }
        return examineList;
    }


    @Override
    public List<Examine> getExamineList(Integer id, Integer type) {

        // 获取未加签的数据
        QueryWrapper<Examine> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(Examine::getStreamType, type)
                .eq(Examine::getCorrelationId, id)
                .eq(Examine::getExamineType, 0)
                .eq(Examine::getAddSignType, 0);
        // 获取流程的基本数据
        List<Examine> examineList = mapper.selectExamineListByTypeAndMainId(queryWrapper);

        // 未加签数据组合
        List<Examine> examines = combinationExamine(examineList);


        // 获取加签数据
        queryWrapper.clear();
        queryWrapper.lambda()
                .eq(Examine::getStreamType, type)
                .eq(Examine::getCorrelationId, id)
                .eq(Examine::getExamineType, 0)
                .ne(Examine::getAddSignType, 0);
        List<Examine> examineList1 = mapper.selectExamineListByTypeAndMainId(queryWrapper);

        if (examineList1.size() != 0) {
            // 加签数据组合
            List<Examine> examines1 = combinationExamine(examineList1);
            // 插入到原始数据中去
            for (int i = 0; i < examines1.size(); i++) {
                Examine examine = examines1.get(i);

                //获取是加签位置
                Integer index = examines.stream().filter(ii -> ii.getExamineUserId().equals(examine.getSignUserId())).map(examineList::indexOf).findFirst().get();

                //当前数据是前加签
                if (examine.getAddSignType() == 1) {
                    examines.add(index, examine);
                }

                //当前数据是后加签
                if (examine.getAddSignType() == 2) {
                    examines.add(index + i + 1, examine);
                }
            }
        }

        return examines;
    }

    private List<Examine> combinationExamine(List<Examine> examineList) {
        // 顺序数据
        List<Examine> examineList1 = examineList.stream().filter(i -> i.getAuditType().equals(1)).collect(Collectors.toList());
        if (examineList1.size() != 0) {
            List<ExamineUser> examineUsers = new ArrayList<>();
            examineList1.forEach(examine -> {

                List<ExamineFile> examineFiles = examineFileMapper.selectList(
                        new LambdaQueryWrapper<ExamineFile>().eq(ExamineFile::getExamineUserId, examine.getExamineUserId())
                );
                if (examineFiles.size() != 0) {
                    examine.setExamineFiles(examineFiles);
                }
            });
        }

        // 会签数据
        List<Examine> examineList2 = examineList.stream().filter(i -> i.getAuditType().equals(2)).collect(Collectors.toList());
        if (examineList2.size() != 0) {
            List<ExamineUser> examineUsers = new ArrayList<>();
            examineList2.forEach(examine -> {

                List<ExamineFile> examineFiles = examineFileMapper.selectList(
                        new LambdaQueryWrapper<ExamineFile>().eq(ExamineFile::getExamineUserId, examine.getExamineUserId())
                );
                if (examineFiles.size() != 0) {
                    examine.setExamineFiles(examineFiles);
                }

                ExamineUser examineUser = new ExamineUser();
                examineUser.setAuditUserId(examine.getExamineAuditUserId());
                examineUser.setStatus(examine.getExamineStatus());
                examineUser.setPreStatus(examine.getExaminePreStatus());
                examineUser.setAuditName(examine.getAuditName());
                examineUser.setExamineFiles(examine.getExamineFiles());
                examineUser.setOpinion(examine.getOpinion());
                examineUsers.add(examineUser);

            });
            Examine examine2 = examineList2.get(0);
            examine2.setExamineUsers(examineUsers);
            examineList1.add(examine2);
        }
        // 并签数据
        List<Examine> examineList3 = examineList.stream().filter(i -> i.getAuditType().equals(3)).collect(Collectors.toList());
        if (examineList3.size() != 0) {
            List<ExamineUser> examineUsers1 = new ArrayList<>();
            examineList3.forEach(examine -> {

                List<ExamineFile> examineFiles = examineFileMapper.selectList(
                        new LambdaQueryWrapper<ExamineFile>().eq(ExamineFile::getExamineUserId, examine.getExamineUserId())
                );
                if (examineFiles.size() != 0) {
                    examine.setExamineFiles(examineFiles);
                }

                ExamineUser examineUser1 = new ExamineUser();
                examineUser1.setAuditUserId(examine.getExamineAuditUserId());
                examineUser1.setStatus(examine.getExamineStatus());
                examineUser1.setPreStatus(examine.getExaminePreStatus());
                examineUser1.setAuditName(examine.getAuditName());
                examineUser1.setExamineFiles(examine.getExamineFiles());
                examineUser1.setOpinion(examine.getOpinion());
                examineUsers1.add(examineUser1);
            });
            Examine examine3 = examineList3.get(0);
            examine3.setExamineUsers(examineUsers1);
            examineList1.add(examine3);
        }
        examineList1.stream().sorted(Comparator.comparing(Examine::getId));

        return examineList1;
    }


    @Override
    public Examine getUserIsAuditBy(Integer adminId, Integer type, Integer mainId) {
        // 数据存在则返回数据
        Examine examine = examineUserMapper.selectAuditById(adminId, type, mainId);
        if (examine == null) {
            return null;
        }
        return examine;
    }

    private FromDetail assemble(Examine examine, FromDetail fromDetail, Integer id, Integer type) {
        switch (type) {
            //报价
            case 1:
                List<Quotes> quotes = Arrays.asList(quotesService.selectDetailById(id));
                fromDetail.setQuotes(quotes);

                // 客户基本信息 拿附件
                Customer customer = customerService.selectDetailById(quotes.get(0).getCustomerId());
                fromDetail.setCustomer(customer);

                // 合同基本数据 拿附件
                Contract contract = contractService.selectByContractId(customer.getId());
                fromDetail.setContract(contract);
                //生产
                List<Produce> produces = produceService.selectListContractId(contract.getId());
                fromDetail.setProduceList(produces);
                //送货
                List<Deliver> delivers = deliverService.selectByContractId(contract.getId());
                fromDetail.setDeliverList(delivers);
                //跟踪记录
                List<Follow> follows = followService.viewByCustomerId(contract.getId());
                fromDetail.setFollowList(follows);
                //回款
                List<CustomerPayment> customerPayments = customerPaymentService.selectByContractId(contract.getId());
                fromDetail.setCustomerPaymentList(customerPayments);
                //计划回款
                List<PlanCollect> planCollects = planCollectService.selectByContractId(contract.getId());
                fromDetail.setPlanCollectList(planCollects);
                break;
            //合同
            case 2:

                Contract contractTwo = contractService.selectByContractId(id);
                fromDetail.setContract(contractTwo);
                //客户基本信息
                Customer customerTwo = customerService.selectDetailById(contractTwo.getCustomerId());
                fromDetail.setCustomer(customerTwo);
                //报价基本信息
//                List<Quotes> quotesTwo = quotesService.selectByCustomerId(customerTwo.getId());
//                fromDetail.setQuotes(quotesTwo);
                //报价产品信息
                List<QuotesProducts> quotesProducts = qpMapper.selectListByContractId(contractTwo.getId());
                fromDetail.setQuotesProducts(quotesProducts);
                //生产产品信息
                List<ProduceProducts> produceProducts = ppMapper.selectListByContractId(contractTwo.getId());
                fromDetail.setProduceProducts(produceProducts);
                //生产
//                List<Produce> producesTwo = produceService.selectListContractId(contractTwo.getId());
//                fromDetail.setProduceList(producesTwo);
                //送货
                List<Deliver> deliversTwo = deliverService.selectByContractId(contractTwo.getId());
                fromDetail.setDeliverList(deliversTwo);
                //跟进记录
                List<Follow> followsTwo = followService.viewByCustomerId(customerTwo.getId());
                fromDetail.setFollowList(followsTwo);
                //回款
                List<CustomerPayment> customerPaymentsTwo = customerPaymentService.selectByContractId(contractTwo.getId());
                fromDetail.setCustomerPaymentList(customerPaymentsTwo);
                //计划回款
                List<PlanCollect> planCollectsTwo = planCollectService.selectByContractId(contractTwo.getId());
                fromDetail.setPlanCollectList(planCollectsTwo);
                break;
            //生产
            case 3:

                List<Produce> producesThree = Arrays.asList(produceService.selectProduceById(id));
                fromDetail.setProduceList(producesThree);
                //合同
                Contract contractThree = contractService.selectByContractId(producesThree.get(0).getContractId());
                fromDetail.setContract(contractThree);
                //客户
                Customer customerThree = customerService.selectDetailById(contractThree.getCustomerId());
                fromDetail.setCustomer(customerThree);
                //报价
                List<Quotes> quotesThree = quotesService.selectByCustomerId(customerThree.getId());
                fromDetail.setQuotes(quotesThree);
                //送货
                List<Deliver> deliversThree = deliverService.selectByContractId(contractThree.getId());
                fromDetail.setDeliverList(deliversThree);
                //跟进记录
                List<Follow> followsThree = followService.viewByCustomerId(customerThree.getId());
                fromDetail.setFollowList(followsThree);
                //回款
                List<CustomerPayment> customerPaymentsThree = customerPaymentService.selectByContractId(contractThree.getId());
                fromDetail.setCustomerPaymentList(customerPaymentsThree);
                //计划回款
                List<PlanCollect> planCollectsThree = planCollectService.selectByContractId(contractThree.getId());
                fromDetail.setPlanCollectList(planCollectsThree);
                break;
            //送货
            case 4:

                List<Deliver> deliversFour = Arrays.asList(deliverService.listByDeliverId(id));
                fromDetail.setDeliverList(deliversFour);
                //合同
                Contract contractFour = contractService.selectByContractId(deliversFour.get(0).getContractId());
                fromDetail.setContract(contractFour);
                //客户
                Customer customerFour = customerService.selectDetailById(contractFour.getCustomerId());
                fromDetail.setCustomer(customerFour);
                //报价
                List<Quotes> quotesFour = quotesService.selectByCustomerId(customerFour.getId());
                fromDetail.setQuotes(quotesFour);
                //生产
                List<Produce> producesFour = produceService.selectListContractId(contractFour.getId());
                fromDetail.setProduceList(producesFour);
                //跟进记录
                List<Follow> followsFour = followService.viewByCustomerId(customerFour.getId());
                fromDetail.setFollowList(followsFour);
                //回款
                List<CustomerPayment> customerPaymentsFour = customerPaymentService.selectByContractId(contractFour.getId());
                fromDetail.setCustomerPaymentList(customerPaymentsFour);
                //计划回款
                List<PlanCollect> planCollectsFour = planCollectService.selectByContractId(contractFour.getId());
                fromDetail.setPlanCollectList(planCollectsFour);
                break;
            //回款
            case 5:
                List<CustomerPayment> customerPaymentFive = Arrays.asList(customerPaymentService.detailById(examine.getCorrelationId()));
                fromDetail.setCustomerPaymentList(customerPaymentFive);
                //合同
//                Contract contractFive = contractService.selectByContractId(customerPaymentFive.get(0).getCustomerId());
//                fromDetail.setContract(contractFive);
//                //客户
//                Customer customerFive = customerService.selectDetailById(contractFive.getCustomerId());
//                fromDetail.setCustomer(customerFive);
//                //报价
//                List<Quotes> quotesFive = quotesService.selectByCustomerId(customerFive.getId());
//                fromDetail.setQuotes(quotesFive);
//                //生产
//                List<Produce> producesFive = produceService.selectListContractId(contractFive.getId());
//                fromDetail.setProduceList(producesFive);
//                //跟进记录
//                List<Follow> followsFive = followService.viewByCustomerId(customerFive.getId());
//                fromDetail.setFollowList(followsFive);
//                //计划回款
//                List<PlanCollect> planCollectsFive = planCollectService.selectByContractId(contractFive.getId());
//                fromDetail.setPlanCollectList(planCollectsFive);
                break;
            //计划回款
            case 6:
                List<PlanCollect> planCollectsSix = Arrays.asList(planCollectService.selectByPlId(id));
                fromDetail.setPlanCollectList(planCollectsSix);
                //合同
                Contract contractSix = contractService.selectByContractId(planCollectsSix.get(0).getContractId());
                fromDetail.setContract(contractSix);
                //客户
                Customer customerSix = customerService.selectDetailById(contractSix.getCustomerId());
                fromDetail.setCustomer(customerSix);
                //报价
                List<Quotes> quotesSix = quotesService.selectByCustomerId(customerSix.getId());
                fromDetail.setQuotes(quotesSix);
                // 生产
                List<Produce> producesSix = produceService.selectListContractId(contractSix.getId());
                fromDetail.setProduceList(producesSix);
                // 跟进记录
                List<Follow> followsSix = followService.viewByCustomerId(customerSix.getId());
                fromDetail.setFollowList(followsSix);
                //回款
                List<CustomerPayment> customerPaymentsSix = customerPaymentService.selectByContractId(contractSix.getId());
                fromDetail.setCustomerPaymentList(customerPaymentsSix);
                break;
            //跟进记录
            case 7:
                List<Follow> followSeven = Arrays.asList(followService.listById(id));
                fromDetail.setFollowList(followSeven);

                //客户
                Customer customerSeven = customerService.selectDetailById(followSeven.get(0).getCustomerId());
                fromDetail.setCustomer(customerSeven);
//                //合同
//                Contract contractSeven = contractService.selectByContractId(customerSeven.getc);
//                fromDetail.setContract(contractSeven);
                //报价
                List<Quotes> quotesSeven = quotesService.selectByCustomerId(customerSeven.getId());
                fromDetail.setQuotes(quotesSeven);
//                //生产
//                List<Produce> produceSeven = produceService.selectListContractId(contractSeven.getId());
//                fromDetail.setProduceList(produceSeven);
//                //送货
//                List<Deliver> deliverSeven = deliverService.selectByContractId(contractSeven.getId());
//                fromDetail.setDeliverList(deliverSeven);
//                //回款
//                List<CustomerPayment> customerPaymentsSeven = customerPaymentService.selectByContractId(contractSeven.getId());
//                fromDetail.setCustomerPaymentList(customerPaymentsSeven);
                break;
            //报销
            case 8:
                Reimbursement reimbursementEight = reimbursementService.selectInfoById(examine.getCorrelationId());
                fromDetail.setReimbursement(reimbursementEight);
                break;
            //借款
            case 9:
                Loan loanNine = loanService.getLoanById(examine.getCorrelationId());
                fromDetail.setLoan(loanNine);
                break;
            //客户
            case 10:
                Customer customerTen = customerService.selectDetailById(id);
                fromDetail.setCustomer(customerTen);
                //合同基本信息
                Contract contractTen = contractService.selectByCustomerId(customerTen.getId());
                fromDetail.setContract(contractTen);
                //报价
                List<Quotes> quotesTen = quotesService.selectByCustomerId(customerTen.getId());
                fromDetail.setQuotes(quotesTen);
                //生产
                List<Produce> producesTen = produceService.selectListContractId(contractTen.getId());
                fromDetail.setProduceList(producesTen);
                //送货
                List<Deliver> deliversTen = deliverService.selectByContractId(contractTen.getId());
                fromDetail.setDeliverList(deliversTen);
                //跟进记录
                List<Follow> followsTen = followService.viewByCustomerId(customerTen.getId());
                fromDetail.setFollowList(followsTen);
                //回款
                //计划回款
                break;
            //付款 15
            case 15:
                Payment paymentById = paymentService.getPaymentById(id);
                fromDetail.setPayment(paymentById);
                break;
            //请购 22
            case 22:
                PurchaseRequisition purchaseRequisition = purchaseRequisitionService.detailById(id);
                fromDetail.setPurchaseRequisition(purchaseRequisition);
                break;
            //采购 23
            case 23:
                Procurement procurement = procurementService.detailById(id);
                fromDetail.setProcurement(procurement);
                break;
            //退货 24
            case 24:
                Procurement returnProcurement = procurementService.detailById(id);
                fromDetail.setReturnProcurement(returnProcurement);
                break;

        }
        return fromDetail;
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void addExamine(AddPageData addPageAop) {
        List<WorkflowJson> workflowJson = addPageAop.getWorkflowJson();
        AtomicReference<Boolean> exemptStatus = new AtomicReference<>(false);
        if (workflowJson.size() != 0) {
            //按照number来分组
            Map<Integer, List<WorkflowJson>> map = workflowJson.stream().collect(Collectors.groupingBy(WorkflowJson::getNumber));
            map.forEach((number, workflowJson1) -> {
                //初次提交就有number则添加到抄送表中
                if (number == 0) {
                    //插入抄送表中
                    workflowJson1.forEach(workflowJson2 -> {
                        if (workflowJson2.getType() == 2) {
                            List<ToSend> toSendList = new ArrayList<>();
                            workflowJson2.getNodeUserList().forEach(admin -> {
                                ToSend toSend = new ToSend();
                                toSend.setExamineType(0);
                                toSend.setCorrelationId(addPageAop.getCorrelationId());
                                toSend.setStreamType(addPageAop.getStreamType());
                                toSend.setToAdmin(admin.getId());
                                toSend.setCreateTime(DateUtil.date());
                                toSendList.add(toSend);
                            });
                            toSendService.saveBatch(toSendList);
                        }
                    });
                }
                if (number > 0) {
                    for (int i = 0; i < workflowJson1.size(); i++) {
                        WorkflowJson workflowJson3 = workflowJson1.get(i);
                        Examine examine = new Examine();
                        if (workflowJson3.getType() == 1) {
                            // 插入审核主表信息
                            examine.setApplicantId(addPageAop.getAdminId());
                            examine.setCorrelationId(addPageAop.getCorrelationId());
                            examine.setTitle(addPageAop.getTitle());
                            examine.setStreamType(addPageAop.getStreamType());
                            examine.setAuditType(workflowJson3.getExamineMode());
                            examine.setIsAddSign(workflowJson3.getIsAddSign());
                            examine.setIsSend(0);
                            examine.setCreateTime(DateUtil.date());
                            mapper.insert(examine);
                            //examine.setAuditOnly(uuId);
                            //examine.setAuditId(admin.getId());
                            //examine.setExamineType(0);
                            // 获取审核人id集合
                            List<Integer> adminIdsList = workflowJson3.getNodeUserList().stream().map(Admin::getId).collect(Collectors.toList());
                            // 根据用户插入当前审核子表信息
                            for (int ii = 0; ii < workflowJson3.getNodeUserList().size(); ii++) {
                                Admin admin = workflowJson3.getNodeUserList().get(ii);
                                ExamineUser examineUser = new ExamineUser();
                                examineUser.setExamineId(examine.getId());
                                examineUser.setAuditUserId(admin.getId());
                                examineUser.setCreateTime(DateUtil.date());
                                examineUser.setStatus(0);
                                // 第一条数据处理
                                if (i == 0) {
                                    // 顺序审核
                                    if (ii == 0 && workflowJson3.getExamineMode() == 1) {
                                        examineUser.setPreStatus(1);
                                    }
                                    // 会审和或审
                                    if (workflowJson3.getExamineMode() != 1) {
                                        examineUser.setPreStatus(1);
                                    }
                                }
                                int option = adminIdsList.indexOf(addPageAop.getAdminId());
                                //客户添加的时候，如果是部门主管添加的，则不用审核,申请人在审核列表中，当前申请人在审核人中的排序
                                if (addPageAop.getExempt() == 1 && adminIdsList.contains(addPageAop.getAdminId()) && ii <= option) {
                                    exemptStatus.set(true);
                                    if (workflowJson3.getExamineMode() == 1) {
                                        examineUser.setStatus(ii <= option ? 1 : 0);
                                    }
                                    // 修改主表数据，当审核列表和当前人在审核列表下表相等时，则直接修改主表数据
                                    if (option == adminIdsList.size() - 1 && ii == option) {
                                        examine.setStatus(1);
                                        mapper.updateById(examine);
                                    }
                                }
                                // 如果超出当前审核列表长度，则表明后续还有人需要审核
                                if (addPageAop.getExempt() == 1 && adminIdsList.contains(addPageAop.getAdminId()) && ii > option) {
                                    if (workflowJson3.getExamineMode() == 1 && ii == option + 1) {
                                        examineUser.setPreStatus(1);
                                    }
                                    exemptStatus.set(false);
                                }
                                //插入子表数据
                                examineUserMapper.insert(examineUser);
                            }
                        }
                        // 抄送处理
                        if (workflowJson3.getType() == 2) {
                            List<Integer> adminIds = workflowJson3.getNodeUserList().stream().map(Admin::getId).collect(Collectors.toList());
                            if (adminIds.size() != 0 && adminIds != null) {
                                // 提交过来的数据有抄送数据
                                examine.setIsSend(1);
                                examine.setIsUpdate(workflowJson3.getUserSelectFlag() != null && workflowJson3.getUserSelectFlag() ? 1 : 0);
                                examine.setToTotalAdmin(Joiner.on(",").join(adminIds));
                                mapper.updateById(examine);
                            }
                        }
                    }
                }
            });
        }
        // 如果当前状态全等于true,则直接修改主表审核状态为审核已通过
        if (exemptStatus.get() == true) {
            updateMainTable(addPageAop.getCorrelationId(), 1, addPageAop.getStreamType(), null);
        } else {
            // 审核提醒，查询所有pre_status上个审核状态为1的数据，那么这就是需要提醒的数据
            List<ExamineUser> examineUsers = examineUserMapper.selectAuditListById(addPageAop.getStreamType(), addPageAop.getCorrelationId());
            examineUsers.forEach(examineUser -> {
                sendPushMsg(examineUser.getAuditUserId(), addPageAop.getAdminId(), 1, addPageAop.getStreamType(), addPageAop.getCorrelationId(), null, null, null);
            });
        }
        // 发送推送消息,抄送提醒
        QueryWrapper<ToSend> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(ToSend::getCorrelationId, addPageAop.getCorrelationId())
                .eq(ToSend::getStreamType, addPageAop.getStreamType())
                .eq(ToSend::getExamineType, 0);
        List<ToSend> toSendList = toSendMapper.selectList(queryWrapper);
        if (toSendList != null && toSendList.size() != 0) {
            // 抄送信息提示
            toSendList.forEach(toSend -> {
                sendPushMsg(toSend.getToAdmin(), addPageAop.getAdminId(), 3, addPageAop.getStreamType(), addPageAop.getCorrelationId(), null, null, null);
            });
        }
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void audit(ExamineUser examineUser) {
        //查询主表数据是否存在审核数据
        Examine examine = examineUserMapper.selectAuditById(examineUser.getAuditUserId(), examineUser.getType(), examineUser.getMainId());
        if (examine == null) {
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        //修改子表信息表
        //examineUser.setUpdateTime(DateUtil.date());
        examineUser.setAuditTime(DateUtil.date());
        examineUserMapper.update(examineUser, new LambdaQueryWrapper<ExamineUser>().eq(ExamineUser::getAuditUserId, examineUser.getAuditUserId()).eq(ExamineUser::getExamineId, examine.getId()));

        // 插入审核附件
        if (examineUser.getExamineFiles() != null && examineUser.getExamineFiles().size() != 0) {
            examineUser.getExamineFiles().forEach(examineFile -> {
                examineFile.setExamineUserId(examine.getExamineUserId());
                examineFile.setCreateTime(DateUtil.date());
                examineFileMapper.insert(examineFile);
            });
        }

        // 审核通过
        if (examineUser.getStatus() == 1) {
            // 获取整个审核数据排列好的列表数据,获取第一次数据
            List<Examine> examineList = getDetailsList(examineUser.getMainId(), examineUser.getType());
            // 获取当前位置
            Integer index = examineList.stream().filter(i -> i.getExamineUserId().equals(examine.getExamineUserId())).map(examineList::indexOf).findFirst().get();

            if (examine.getAuditType() == 1 || examine.getAuditType() == 2) {
                // 先检测该审核分组是否其他数据，如果没有主表信息status 更改为状态
                List<Examine> isExitList = examineList.stream().filter(i -> i.getId().equals(examine.getId()) && i.getExamineStatus().equals(0)).collect(Collectors.toList());
                if (isExitList.size() == 0) {
                    // 修改审核主表信息
                    examine.setStatus(examineUser.getStatus());
                    mapper.updateById(examine);
                }
            }

            if (examine.getAuditType() == 3) {
                // 修改审核主表信息
                examine.setStatus(examineUser.getStatus());
                mapper.updateById(examine);
            }

            // 获取第二次更新主表之后的数据
            List<Examine> examineList1 = getDetailsList(examineUser.getMainId(), examineUser.getType());

            // 检测是否还有其他审核存在其他审核分组数据
            List<Examine> isTotalExitList = examineList1.stream().filter(i -> i.getStatus().equals(0) && i.getExamineStatus().equals(0)).collect(Collectors.toList());

            if (isTotalExitList.size() == 0) {
                //所有状态更改成通过，并修改主表
                updateMainTable(examine.getCorrelationId(), examineUser.getStatus(), examine.getStreamType(), examine.getExamineType());
                sendPushMsg(examine.getApplicantId(), examineUser.getAuditUserId(), 2, examine.getStreamType(), examine.getCorrelationId(), null, null, examine.getExamineType());
            } else {
                Examine examine1 = isTotalExitList.get(0);
                //顺序审核
                if (examine1.getAuditType() == 1) {
                    //更新当这条数据
                    ExamineUser examineUser1 = new ExamineUser();
                    examineUser1.setId(examine1.getExamineUserId());
                    examineUser1.setPreStatus(examineUser.getStatus());
                    examineUserMapper.updateById(examineUser1);
                    // 通知下一审核人
                    sendPushMsg(examineUser.getAuditUserId(), examine1.getExamineAuditUserId(), 4, examine1.getStreamType(), examine1.getCorrelationId(), examine1.getExamineAuditUserId(), null, examine1.getExamineType());
                }
                // 会审和或审,pre_status 状态为 0 的数据,第二次不满足条件
                if (examine1.getExaminePreStatus() == 0 && (examine1.getAuditType() == 2 || examine1.getAuditType() == 3)) {
                    List<Examine> examineList2 = examineList1.stream().filter(i -> i.getId().equals(examine1.getId())).collect(Collectors.toList());
                    //修改子表信息
                    examineList2.forEach(examine2 -> {
                        ExamineUser examineUser2 = new ExamineUser();
                        examineUser2.setId(examine2.getExamineUserId());
                        examineUser2.setPreStatus(examineUser.getStatus());
                        examineUserMapper.updateById(examineUser2);
                        //发送推送消息给会审或者或审的人
                        sendPushMsg(examineUser.getAuditUserId(), examine1.getExamineAuditUserId(), examine1.getAuditType() == 2 ? 6 : 7, examine2.getStreamType(), examine2.getCorrelationId(), null, null, examine2.getExamineType());
                    });

                }

                //处理抄送
                if (examine.getIsSend() == 1 && isTotalExitList.size() != 0) {
                    String adminStr = examine.getToTotalAdmin();
                    if (StrUtil.isNotBlank(adminStr)) {
                        List<Integer> adminIds = CovertUtil.covertIntegerList(adminStr);
                        List<ToSend> toSendList = new ArrayList<>();
                        if (examine.getAuditType() == 1 || examine.getAuditType() == 2) {
                            adminIds.forEach(admin -> {
                                ToSend toSend = new ToSend();
                                toSend.setExamineType(1);
                                toSend.setCorrelationId(examine.getCorrelationId());
                                toSend.setStreamType(examine.getStreamType());
                                toSend.setToAdmin(admin);
                                toSend.setCreateTime(DateUtil.date());
                                toSendList.add(toSend);
                                sendPushMsg(toSend.getToAdmin(), examineUser.getAuditUserId(), 3, examine.getStreamType(), examine.getCorrelationId(), null, null, examine.getExamineType());
                            });
                        }
                        if (examine.getAuditType() == 3) {
                            adminIds.forEach(admin -> {
                                ToSend toSend = new ToSend();
                                toSend.setExamineType(1);
                                toSend.setCorrelationId(examine.getCorrelationId());
                                toSend.setStreamType(examine.getStreamType());
                                toSend.setToAdmin(admin);
                                toSend.setCreateTime(DateUtil.date());
                                toSendList.add(toSend);
                                sendPushMsg(toSend.getToAdmin(), examineUser.getAuditUserId(), 3, examine.getStreamType(), examine.getCorrelationId(), null, null, examine.getExamineType());
                            });
                        }
                        toSendService.saveBatch(toSendList);
                    }
                }
            }
        }

        // 审核不通过
        if (examineUser.getStatus() == 2) {
            //处理抄送
            if (examine.getIsSend() == 1) {
                String adminStr = examine.getToTotalAdmin();
                if (StrUtil.isNotBlank(adminStr)) {
                    List<Integer> adminIds = CovertUtil.covertIntegerList(adminStr);
                    List<ToSend> toSendList = new ArrayList<>();
                    adminIds.forEach(admin -> {
                        ToSend toSend = new ToSend();
                        toSend.setExamineType(1);
                        toSend.setCorrelationId(examine.getCorrelationId());
                        toSend.setStreamType(examine.getStreamType());
                        toSend.setToAdmin(admin);
                        toSend.setCreateTime(DateUtil.date());
                        toSendList.add(toSend);
                        sendPushMsg(toSend.getToAdmin(), examine.getExamineAuditUserId(), 3, examine.getStreamType(), examine.getCorrelationId(), null, null, examine.getExamineType());
                    });
                    toSendService.saveBatch(toSendList);
                }
            }

            // 修改审核主表信息
            examine.setStatus(examineUser.getStatus());
            mapper.updateById(examine);

            updateMainTable(examine.getCorrelationId(), examineUser.getStatus(), examine.getStreamType(), 0);
            sendPushMsg(examine.getApplicantId(), examineUser.getAuditUserId(), 5, examine.getStreamType(), examine.getCorrelationId(), null, null, examine.getExamineType());
        }
    }

    /**
     * 更新主表审核状态
     *
     * @param mainId        主表id
     * @param status        状态
     * @param operationCode 流程code
     */
    private void updateMainTable(Integer mainId, Integer status, Integer operationCode, Integer examineType) {
        // 修改主表状态以及id
        switch (operationCode) {
            //报价
            case 1:
                if (examineType == null || examineType == 0) {
                    Quotes quotes = quotesService.selectDetailById(mainId);
                    quotes.setStatus(status);
                    quotesService.updateById(quotes);
                } else {
                    //反审核
                    antiAuditOperation(operationCode, mainId);
                }
                break;
            //合同
            case 2:
                if (examineType == null || examineType == 0) {
                    Contract contract = contractService.getById(mainId);
                    contract.setStatus(status);
                    contractService.updateById(contract);
                    if (status == 1) {
                        //则自动生成单子
                        contractService.generateList(contract);
                    } else {
                        //审核不通过则修改报价的审核状态
                        Quotes quotes = new Quotes();
                        quotes.setId(contract.getQuotesId());
                        quotes.setIsContract(0);
                        quotes.setUpdateTime(DateUtil.date());
                        quotesService.updateById(quotes);
                    }
                } else {
                    QueryWrapper<Produce> wrapper = new QueryWrapper<>();
                    wrapper.lambda().eq(Produce::getContractId, mainId)
                            .eq(Produce::getType, 2);
                    List<Produce> produces = produceMapper.selectList(wrapper);
                    if (produces.size() != 0) {
                        throw new CustomException(ResultCode.PRODUCE_IS_NOT_MODIFY);
                    } else {
                        antiAuditOperation(operationCode, mainId);
                    }
                }

                break;
            //生产
            case 3:
                Produce produce = produceService.getById(mainId);
                produce.setStatus(status);
                produceService.updateById(produce);
                break;
            //送货
            case 4:
                Deliver deliver = deliverService.getById(mainId);
                deliver.setStatus(status);
                deliverService.updateById(deliver);
                break;
            //回款
            case 5:
                CustomerPayment customerPayment = customerPaymentService.detailById(mainId);
                customerPayment.setStatus(status);
                //则自动生成单子
                if (status == 1 && customerPayment.getPaymentType() == 1) {
//                    Contract contract1 = contractService.selectByContractId(customerPayment.getContractId());
                    planCollectService.generateList(customerPayment, true);
                } else if (status == 1 && customerPayment.getPaymentType() == 3) {
                    billService.updateBillCustomer(customerPayment);
                }
                customerPaymentService.updateById(customerPayment);
                break;
            //回款计划
            case 6:
                PlanCollect planCollect = planCollectService.getById(mainId);
                planCollect.setStatus(status);
                planCollectService.updateById(planCollect);
                break;
            //跟进记录
            case 7:
                Follow follow = followService.getById(mainId);
                follow.setStatus(status);
                followService.updateById(follow);
                break;
            //报销
            case 8:
                Reimbursement reimbursement = reimbursementService.getById(mainId);
                reimbursement.setStatus(status);
                reimbursementService.updateById(reimbursement);
                break;
            //借款
            case 9:
                Loan loan = loanService.getById(mainId);
                loan.setStatus(status);
                loanService.updateById(loan);
                break;
            //客户
            case 10:
                if (examineType == null || examineType == 0) {
                    Customer customer = customerService.getById(mainId);
                    customer.setStatus(status);
                    customerService.updateById(customer);
                } else {
                    antiAuditOperation(operationCode, mainId);
                }
                break;
            //请假
            case 13:
                attendanceLeaveService.auditLeave(status, mainId);
                break;
            //付款
            case 15:
                Payment payment = paymentMapper.selectById(mainId);
                payment.setStatus(status);
                paymentMapper.updateById(payment);
                break;
            case 16:
                refundService.auditStatus(mainId, status);
                break;
            case 22:
                //请购
                PurchaseRequisition purchaseRequisition = purchaseRequisitionMapper.selectById(mainId);
                purchaseRequisition.setStatus(status);
                purchaseRequisition.setRequisitionState(status);
                purchaseRequisitionMapper.updateById(purchaseRequisition);
                break;
            case 23:
                //采购
                Procurement procurement = procurementMapper.selectById(mainId);
                procurement.setStatus(status);
                procurement.setArrivalState(1);
                procurementMapper.updateById(procurement);
                break;
            case 24:
                //退货
                Procurement procurement1 = procurementMapper.selectById(mainId);
                procurement1.setStatus(status);
                procurement1.setArrivalState(3);
                procurementService.updateById(procurement1);
                break;
            case 25:
                //生产退货
                Rejected rejected = rejectedMapper.selectById(mainId);
                rejected.setStatus(status);
                rejectedMapper.updateById(rejected);
                break;
        }

    }


    /**
     * 推送消息
     *
     * @param toId          接收人
     * @param fromId        发送人
     * @param type          通知类型
     * @param operationType 通知流程
     * @param correlationId 主表id
     * @param examineType   审核流程类型
     */
    private void sendPushMsg(Integer toId, Integer fromId, Integer type, Integer operationType, Integer correlationId, Integer nextAdminId, List<Integer> adminIds, Integer examineType) {
        DoReminder doReminder = new DoReminder();
        //接收人
        doReminder.setAdminId(toId);
        //发送人
        doReminder.setFromId(fromId);
        //抄送提醒
        doReminder.setType(examineType == null || examineType == 0 ? type : 10);
        doReminder.setCorrlelationId(correlationId);
        doReminder.setCreateTime(DateUtil.date());
        doReminder.setNextAdminId(nextAdminId);
        doReminder.setAdminIds(adminIds);
        //doReminder.setUrlAddress(sendReminder.pushUrl());
        doReminder.setOperationType(operationType);
        reminderService.addDoReminder(doReminder);
    }


    @Override
    public void antiAuditOperation(Integer streamType, Integer correlationId) {
        ModifyLog modifyLog = new ModifyLog();
        modifyLog.setCorrelationId(correlationId);
        modifyLog.setStreamType(streamType);
        modifyLogService.modifyLogAdd(modifyLog);
//        QueryWrapper<Examine> wrapper = new QueryWrapper<>();
//        wrapper.lambda().eq(Examine::getStreamType, streamType)
//                .eq(Examine::getCorrelationId, correlationId)
//                .eq(Examine::getExamineType, 0);
//        Examine examine = new Examine();
//        examine.setStatus(0);
        List<Examine> examines = getDetailsList(correlationId, streamType);
        Integer initId = 0;
        for (int i = 0; i < examines.size(); i++) {
            Examine examine = examines.get(i);
            examine.setStatus(0);
            //更新时间
            examine.setUpdateTime(DateUtil.date());
            mapper.updateById(examine);
            // 修改子表信息
            ExamineUser examineUser = new ExamineUser();
            examineUser.setId(examine.getExamineUserId());
            examineUser.setStatus(0);
            if (i == 0) {
                examineUser.setPreStatus(1);
                if (examine.getAuditType() != 1) {
                    initId = examine.getId();
                }
            }
            if (examine.getAuditType() != 1 && examine.getId().equals(initId)) {
                examineUser.setPreStatus(1);
            }
            examineUser.setUpdateTime(DateUtil.date());
            examineUserMapper.updateById(examineUser);
        }
        switch (streamType) {
            case 1:
                quotesService.antiAudit(correlationId);
                break;
            case 2:
                contractService.antiAudit(correlationId);
                break;
            case 10:
                customerService.antiAudit(correlationId);
                break;
//            case 5:
//                customerPaymentService.antiAudit(correlationId);
//                break;
//            case 15:
//                paymentService.antiAudit(correlationId);
//                break;
//            case 22:
//                purchaseRequisitionService.antiAudit(correlationId);
//                break;
//            case 23:
//                procurementService.antiAudit(correlationId);
//                break;
//            case 24:
//                procurementService.antiAudit(correlationId);
//                break;
        }
    }


    @Override
    public void addOperation(Examine examine) {
        if (examine.getStreamType() == 2) {
            QueryWrapper<Produce> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(Produce::getContractId, examine.getCorrelationId())
                    .ne(Produce::getType, 0);
            List<Produce> produces = produceMapper.selectList(wrapper);
            if (produces.size() != 0) {
                throw new CustomException(ResultCode.PRODUCE_IS_NOT_MODIFY);
            }
        }
        //查询当前申请是否有重复数据
        LambdaQueryWrapper<Examine> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Examine::getStreamType, examine.getStreamType())
                .eq(Examine::getCorrelationId, examine.getCorrelationId())
                .eq(Examine::getStatus, 0).eq(Examine::getExamineType, 1);
        Examine examine1 = mapper.selectOne(queryWrapper);
        if (examine1 != null) {
            throw new CustomException(ResultCode.DATE_APPLICATION_IS_EXISTS);
        }
        List<Admin> admins = positionService.levelPermissions(1, examine.getDepartmentId().toString());
        ExamineUser examineUser = new ExamineUser();
        //如果当前的审核人等于申请人的话
        if (admins.get(0).getId().equals(examine.getApplicantId())) {
            examine.setStatus(1);
//            examine.setTotalStatus(1);
            examineUser.setStatus(1);
            // 申请人的id
            antiAuditOperation(examine.getStreamType(), examine.getCorrelationId());
        }

//        String uuId = UUID.randomUUID().toString().replace("-", "");
//        examine.setAuditId(examines.get(0).getAuditId());
        examine.setCreateTime(DateUtil.date());
//        examine.setAuditOnly(uuId);
        examine.setAuditType(1);
//        examine.setPreStatus(1);
        examine.setExamineType(1);
        mapper.insert(examine);

        // 添加子表信息
        examineUser.setExamineId(examine.getId());
        examineUser.setPreStatus(1);
        examineUser.setOpinion(examine.getOpinion());
        examineUser.setAuditUserId(admins.get(0).getId());
        examineUser.setCreateTime(DateUtil.date());
        examineUserMapper.insert(examineUser);

        // 发送推送消息
        sendPushMsg(examineUser.getAuditUserId(), examine.getApplicantId(), 11, examine.getStreamType(), examine.getCorrelationId(), null, null, null);
    }

    @Override
    public void addSign(Examine examine) {
        // 获取当前审核列表的位置
        List<Examine> examineList = getDetailsList(examine.getCorrelationId(), examine.getStreamType());

        Integer index = examineList.stream().filter(i -> i.getExamineUserId().equals(examine.getSignUserId())).map(examineList::indexOf).findFirst().get();

        //判断是否可以前加签
        if (examine.getAddSignType() == 1) {
            if (index - 1 >= 0) {
                Examine examine1 = examineList.get(index - 1);
                if (examine1 != null) {
                    if (examine1.getAuditType() == 2 || examine1.getAuditType() == 3) {
                        throw new CustomException(ResultCode.AUTH_ADD_SIGN_NOT_ALLOW);
                    }
                }
                // 修改当前数据的pre_status状态，上个审核状态为未审核状态
//                ExamineUser examineUser = new ExamineUser();
//                examineUser.setId(examine.getExamineUserId());
//                examineUser.setPreStatus(0);
//                examineUser.setUpdateTime(DateUtil.date());
//                examineUserMapper.updateById(examineUser);
            }

            // 修改当前数据的pre_status状态，上个审核状态为未审核状态
            ExamineUser examineUser = new ExamineUser();
            examineUser.setId(examine.getSignUserId());
            examineUser.setPreStatus(0);
            examineUser.setUpdateTime(DateUtil.date());
            examineUserMapper.updateById(examineUser);
        }

        // 判断是否可以后置加签
        if (examine.getAddSignType() == 2) {
            if (examineList.size() > index + 1) {
                Examine examine2 = examineList.get(index + 1);
                if (examine2.getAuditType() == 2 || examine2.getAuditType() == 3) {
                    throw new CustomException(ResultCode.AUTH_ADD_SIGN_NOT_ALLOW);
                }
            }
            // 不用修改pre_status状态
        }
        examine.setCreateTime(DateUtil.date());
        //插入主表信息
        mapper.insert(examine);

        if (StrUtil.isNotBlank(examine.getExamineAuditUserIds())) {
            List<Integer> adminIds = CovertUtil.covertIntegerList(examine.getExamineAuditUserIds());
            for (int i = 0; i < adminIds.size(); i++) {
                Integer adminId = adminIds.get(i);
                ExamineUser examineUser = new ExamineUser();

                if (examine.getAddSignType() == 1 && (examine.getAuditType() == 1 && i == 0) ) {
                    examineUser.setPreStatus(1);
                }
                if (examine.getAddSignType() == 1 && (examine.getAuditType() == 2 || examine.getAuditType() == 3)) {
                    examineUser.setPreStatus(1);
                }
                examineUser.setExamineId(examine.getId());
                examineUser.setAuditUserId(adminId);

                examineUser.setCreateTime(DateUtil.date());
                examineUserMapper.insert(examineUser);
            }
        }
    }
}
